package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.hmdp.utils.RedisConstants.GROUP_NAME;
import static com.hmdp.utils.RedisConstants.QUEUE_NAME;

/**
 * <p>
 *  服务实现类
 * </p>

 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    RedisIdWorker redisIdWorker;

    @Autowired
    private ApplicationContext applicationContext; // 注入应用上下文


    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //异步处理的线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    /**
     * VoucherOrderServiceImpl类的代理对象
     * 将代理对象的作用域进行提升，方面子线程取用
     */
    private IVoucherOrderService proxy;

    //创建一个阻塞队列
    // private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024*1024);
    //在类初始化之后执行，因为当这个类初始化好了之后，随时都是有可能要执行的
    @PostConstruct
    public void init() {

        //创建消息队列
        DefaultRedisScript<Long> mqScript = new DefaultRedisScript<>();
        mqScript.setLocation(new ClassPathResource("createQueue.lua"));
        mqScript.setResultType(Long.class);
        Long result = null;

        try {
            result = stringRedisTemplate.execute(mqScript, Collections.emptyList(), QUEUE_NAME, GROUP_NAME);
        } catch (Exception e) {
            log.error("队列创建失败");
            return;
        }

        int r = result.intValue();
        String info = r == 1 ? "队列创建成功" : "队列已存在";
        log.debug(info);
        //执行线程任务
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    // 用于线程池处理的任务
    //当初始化完毕后，就会去从对列中去拿信息

    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {

            while (true) {

                try {
                    // 1.获取消息队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS s1 >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(Consumer.from(GROUP_NAME, "c1")
                            , StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2))
                            , StreamOffset.create(QUEUE_NAME, ReadOffset.lastConsumed()));

                    //2.判断订单消息是否为空
                    if (list == null || list.isEmpty()) {
                        //2.1消息获取失败，说明没有消息，进行下一次消息获取
                        continue;
                    }
                    //3.消息不为空，则解析消息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //3.创建订单
                    handleVoucherOrder(voucherOrder);
                    //4.确认消息 XACK
                    stringRedisTemplate.opsForStream().acknowledge(QUEUE_NAME, GROUP_NAME, record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    //处理异常消息
                    handlePendingList();
                }

            }
        }
    }

        private void handlePendingList() {

            while (true) {
                try {
                    // 1.获取消息队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS s1 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(Consumer.from(GROUP_NAME, "c1")
                            , StreamReadOptions.empty().count(1)
                            , StreamOffset.create( QUEUE_NAME, ReadOffset.from("0"))
                    );

                    //2.判断订单消息是否为空
                    if (list == null || list.isEmpty()) {
                        //2.1消息获取失败，说明没有异常消息，直接break
                        break;
                    }
                    //3.消息不为空，则解析消息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //3.创建订单
                    handleVoucherOrder(voucherOrder);
                    //4.确认消息 XACK
                    stringRedisTemplate.opsForStream().acknowledge(QUEUE_NAME, GROUP_NAME, record.getId());
                } catch (Exception e) {
                    log.error("处理pending订单异常", e);

                    try {
                        Thread.sleep(200);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }

        private void handleVoucherOrder(VoucherOrder voucherOrder) {

          if(proxy == null){
              // 延迟获取代理对象，直到第一次使用
              proxy = applicationContext.getBean(IVoucherOrderService.class);
          }

            //1.获取用户Id
            Long userId = voucherOrder.getUserId();
            //2.创建锁对象
            RLock redisLock = redissonClient.getLock("lock:order:" + userId);
            //3.获取锁
            boolean isLock = redisLock.tryLock();

            if (!isLock) {
                //获取锁失败直接返回失败或重试
                log.error("不允许重复下单");
                return;
            }

            try {
                proxy.createVoucherOrder(voucherOrder);
            } finally {
                //释放锁
                redisLock.unlock();
            }


        }




        @Transactional
        @Override
        public Result seckillVoucher(Long vouchId) {
            //获取用户
            Long userId = UserHolder.getUser().getId();
            Long orderId = redisIdWorker.nextId("order");
            //1.执行lua脚本
            Long result = stringRedisTemplate.execute(SECKILL_SCRIPT, Collections.emptyList()
                    , vouchId.toString(), userId.toString(), orderId.toString());

            int b = result.intValue();
            //2.判断结果是否为0
            if (b != 0) {
                //2.1不为0代表没有购买资格
                return Result.fail(b == 1 ? "库存不足" : "不能重复下单");
            }

            //3.返回订单Id
            return Result.ok(orderId);


        }


        @Transactional
        public void createVoucherOrder(VoucherOrder voucherOrder) {

            Long userId = voucherOrder.getUserId();

            //5.1查询订单
            Long count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();

            if (count >= 1) {
                //当前用户不是一单
                log.error("不能重复下单");
                return;
            }

            //扣减库存
            boolean success = seckillVoucherService.update().setSql("stock=stock -1")
                    .eq("voucher_id", voucherOrder.getVoucherId()).gt("stock", 0).update();

            if (!success) {
                log.error("库存不足");
                return;
            }
            save(voucherOrder);
        }


        /**
         * 抢购秒杀券
         * @param vouchId
         * @return
         */
//    @Transactional
//    @Override
//    public Result seckillVoucher(Long vouchId) {
//        //1.查询秒杀卷
//        SeckillVoucher voucher = seckillVoucherService.getById(vouchId);
//        //2.判断秒杀卷是否合法
//        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
//            return Result.fail("秒杀尚未开始!");
//        }
//        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
//            return Result.fail("秒杀已经结束!");
//        }
//        if(voucher.getStock()< 1){
//            return Result.fail("库存不足");
//        }
//
//        //3.创建订单
//        Long userId =UserHolder.getUser().getId();
//          //创建一个锁对象
//        // SimpleRedisLock lock = new SimpleRedisLock("order" + userId, stringRedisTemplate);
//         //用Redisson来获取锁(可重入),指定锁的名称
//        RLock lock = redissonClient.getLock("lock:order"+userId);
//        //尝试获取锁，参数分别是：获取锁的最大等待时间(期间会重试)，锁自动释放时间，时间单位,不写会有默认值
//        boolean isLock = lock.tryLock();
//        //加锁失败
//        if(!isLock){
//            return Result.fail("不允许重复下单");
//        }
//
//        try {
//            //创建代理对象，使用代理对象调用第三方事务，防止事务失效
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(userId, vouchId);
//        }finally {
//            //释放锁
//            lock.unlock();
//        }
//
//    }
//
//    @Transactional
//    public Result createVoucherOrder(Long userId, Long voucherId) {
//
//
//      //判断当前用户是否是第一单
//         Long count = query().eq("user_id",userId).eq("voucher_id",voucherId).count();
//
//         if(count >= 1){
//             //当前用户不是一单
//             return Result.fail("用户已购买过该优惠券");
//         }
//
//        //扣减库存
//        boolean success = seckillVoucherService.update().setSql("stock=stock -1")
//                .eq("voucher_id", voucherId).gt("stock",0).update();
//
//        if(!success){
//            return Result.fail("秒杀券扣减失败");
//        }
//
//        //6.创建订单
//        VoucherOrder voucherOrder = new VoucherOrder();
//        //6.1订单Id
//        long orderId = redisIdWorker.nextId("order");
//        voucherOrder.setId(orderId);
//        //6.2用户Id
//        voucherOrder.setUserId(userId);
//        //6.3优惠券Id
//        voucherOrder.setVoucherId(voucherId);
//        boolean flag = this.save(voucherOrder);
//        if(!flag){
//            return Result.fail("创建秒杀券订单失败");
//        }
//
//        return Result.ok(orderId);
//    }
    }

